package com.example.email_start;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Component
public class MailUtils {

   @Value("${spring.mail.username}")
   private String sender;

    //发送邮件工具类
    @Autowired(required = false)
    private JavaMailSender javaMailSender;

    //发送简单邮件
    public void sendSimpleMailMessage(String to, String subject, String content){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setFrom(sender);
        simpleMailMessage.setText(content);
        javaMailSender.send(simpleMailMessage);
    }
    // 发送包含图片的邮件
    public void mailMessage(String to,String subject,String content,String[] filePath) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setSubject(subject);

        helper.setText("<div style=\"color: red\">"+content+"</div>",true);
        int i = 1;
        for (String s : filePath) {
            String[] split = s.split("\\.");
            helper.addAttachment("附件"+(i++)+"."+split[1],new File(s));
        }
        helper.setTo(to);
        helper.setFrom(sender);
        javaMailSender.send(message);
    }
}
